const express = require('express');
const authService = require('../services/authService');
const { authMiddleware, roleMiddleware } = require('../middleware/auth');

const router = express.Router();

/**
 * POST /api/auth/login
 * 用户登录
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 获取客户端IP
    const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    const result = await authService.login(username, password, ip);

    if (result.success) {
      res.json(result);
    } else {
      res.status(401).json(result);
    }
  } catch (error) {
    console.error('登录失败:', error.message);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
});

/**
 * GET /api/auth/me
 * 获取当前登录用户信息
 */
router.get('/me', authMiddleware, async (req, res) => {
  try {
    const user = await authService.getUserById(req.user.userId);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      user
    });
  } catch (error) {
    console.error('获取用户信息失败:', error.message);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

/**
 * POST /api/auth/change-password
 * 修改密码
 */
router.post('/change-password', authMiddleware, async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;

    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '旧密码和新密码不能为空'
      });
    }

    if (newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度不能少于6位'
      });
    }

    const result = await authService.changePassword(
      req.user.userId,
      oldPassword,
      newPassword
    );

    res.json(result);
  } catch (error) {
    console.error('修改密码失败:', error.message);
    res.status(500).json({
      success: false,
      message: '修改密码失败'
    });
  }
});

/**
 * POST /api/auth/users
 * 创建用户（仅管理员）
 */
router.post('/users', authMiddleware, roleMiddleware(['admin']), async (req, res) => {
  try {
    const { username, password, realName, employeeId, email, phone, role } = req.body;

    if (!username || !password || !realName) {
      return res.status(400).json({
        success: false,
        message: '用户名、密码和真实姓名不能为空'
      });
    }

    const result = await authService.createUser({
      username,
      password,
      realName,
      employeeId,
      email,
      phone,
      role
    });

    res.json(result);
  } catch (error) {
    console.error('创建用户失败:', error.message);
    res.status(500).json({
      success: false,
      message: '创建用户失败'
    });
  }
});

/**
 * GET /api/auth/users
 * 获取用户列表（仅管理员）
 */
router.get('/users', authMiddleware, roleMiddleware(['admin']), async (req, res) => {
  try {
    const { page = 1, pageSize = 20 } = req.query;

    const result = await authService.getUserList(
      parseInt(page),
      parseInt(pageSize)
    );

    res.json(result);
  } catch (error) {
    console.error('获取用户列表失败:', error.message);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
});

/**
 * PUT /api/auth/users/:id
 * 更新用户信息（仅管理员）
 */
router.put('/users/:id', authMiddleware, roleMiddleware(['admin']), async (req, res) => {
  try {
    const { id } = req.params;
    const { realName, employeeId, role, email, phone, status } = req.body;

    const result = await authService.updateUser(parseInt(id), {
      realName,
      employeeId,
      role,
      email,
      phone,
      status
    });

    res.json(result);
  } catch (error) {
    console.error('更新用户失败:', error.message);
    res.status(500).json({
      success: false,
      message: '更新用户失败'
    });
  }
});

/**
 * DELETE /api/auth/users/:id
 * 删除用户（仅管理员）
 */
router.delete('/users/:id', authMiddleware, roleMiddleware(['admin']), async (req, res) => {
  try {
    const { id } = req.params;

    // 不能删除自己
    if (parseInt(id) === req.user.userId) {
      return res.status(400).json({
        success: false,
        message: '不能删除当前登录用户'
      });
    }

    const result = await authService.deleteUser(parseInt(id));

    res.json(result);
  } catch (error) {
    console.error('删除用户失败:', error.message);
    res.status(500).json({
      success: false,
      message: '删除用户失败'
    });
  }
});

/**
 * POST /api/auth/users/:id/reset-password
 * 重置用户密码（仅管理员）
 */
router.post('/users/:id/reset-password', authMiddleware, roleMiddleware(['admin']), async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;

    if (!newPassword || newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度不能少于6位'
      });
    }

    const result = await authService.resetUserPassword(parseInt(id), newPassword);

    res.json(result);
  } catch (error) {
    console.error('重置密码失败:', error.message);
    res.status(500).json({
      success: false,
      message: '重置密码失败'
    });
  }
});

module.exports = router;

